package com.jinzhi.jzweb.controller;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.common.utils.UnzipUtils;
import com.jinzhi.oss.service.OssService;
import jodd.io.ZipUtil;
import org.apache.http.entity.ContentType;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.jzweb.domain.CertificateManagementDO;
import com.jinzhi.jzweb.service.CertificateManagementService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2022-12-13 10:03:27 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/certificateManagement")
public class CertificateManagementController extends BaseController {
	@Autowired
	private CertificateManagementService certificateManagementService;

	@Autowired
	private OssService ossService;

//	private static String uploadFileUrl = "D:/test/"; //存放压缩包的文件路径
//
//	private static String unzipFileUrl = "D:/test/jy/"; //解压后的文件位置


	private static String uploadFileUrl = "/opt/certificateManagement/"; //存放压缩包的文件路径

	private static String unzipFileUrl = "/opt/certificateManagement/jy/"; //解压后的文件位置



	@GetMapping()
	@RequiresPermissions("jzweb:certificateManagement:certificateManagement")
	String CertificateManagement(){
	    return "jzweb/certificateManagement/certificateManagement";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:certificateManagement:certificateManagement")
	public Result<Page<CertificateManagementDO>> list(CertificateManagementDO certificateManagementDTO){
		EntityWrapper<CertificateManagementDO> entityWrapper = new EntityWrapper();
		if (StringUtil.notEmpty(certificateManagementDTO.getName())){
			entityWrapper.eq("name",certificateManagementDTO.getName());
		}
		entityWrapper.orderBy("id");


		// 查询列表数据
		Page<CertificateManagementDO> page = certificateManagementService.selectPage(getPage(CertificateManagementDO.class),entityWrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
				CertificateManagementDO obj = (CertificateManagementDO) page.getRecords().get(i);
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:certificateManagement:add")
	String add(){
	    return "jzweb/certificateManagement/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:certificateManagement:edit")
	String edit(@PathVariable("id") Long id,Model model){
		CertificateManagementDO certificateManagement = certificateManagementService.selectById(id);
		model.addAttribute("certificateManagement", certificateManagement);
	    return "jzweb/certificateManagement/edit";
	}
	
	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:certificateManagement:add")
	public Result<String> save( CertificateManagementDO certificateManagement){
		certificateManagementService.insert(certificateManagement);
        return Result.ok();
	}
	
	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:certificateManagement:edit")
	public Result<String>  update( CertificateManagementDO certificateManagement){
		boolean update = certificateManagementService.updateById(certificateManagement);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:certificateManagement:remove")
	public Result<String>  remove( Long id){
		certificateManagementService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:certificateManagement:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		certificateManagementService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}



	@PostMapping( "/uploadCertificateManagement")
	@ResponseBody
	@Transactional
	public Result<?> uploadCertificateManagement(@RequestParam("file") MultipartFile file){
		List<CertificateManagementDO> certificateManagementDOS= new ArrayList<>();
		if (file.isEmpty()){
			return Result.fail("文件为空");
		}
		String filename = file.getOriginalFilename(); //获取文件名称
		File dest =new File(new File(uploadFileUrl).getAbsolutePath() + "/"+filename);

		try {
			file.transferTo(dest); //将目标文件上传到指定路径
			filename = uploadFileUrl + filename; //拼接文件的全路径
			UnzipUtils.unzipFile(filename, unzipFileUrl);//将文件解压到指定路径
			deleteFile(new File(uploadFileUrl)); //解压后删除压缩包

			File[] files = new File(unzipFileUrl).listFiles(); //获取所有解压后的文件
			for (File f : files) {
				CertificateManagementDO certificateManagementDO =new CertificateManagementDO();
				String name = f.getName();
				certificateManagementDO.setName(name.substring(0, name.indexOf("("))); //截取学生姓名
				certificateManagementDO.setIdNumber(name.substring(name.indexOf("(")+1, name.indexOf(")"))); //截取身份证号码
				certificateManagementDO.setState(0); //默认证书状态为正常
				certificateManagementDO.setOperatorId(getUserId().toString()); // 操作人id
				certificateManagementDO.setCreateTime(new Date()); //创建时间


				MultipartFile mFile = null;
				File vaf = new File(unzipFileUrl + name);
				FileInputStream fileInputStream = new FileInputStream(vaf);
				String fileName = vaf.getName();
				fileName = fileName.substring((fileName.lastIndexOf("/") + 1));
				mFile =  new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
				String  url = ossService.uploadFileOss2(mFile);
				certificateManagementDO.setUrl(url); //证书路径
				certificateManagementDOS.add(certificateManagementDO);

			}
			certificateManagementService.insertBatch(certificateManagementDOS);
			deleteFile(new File(unzipFileUrl)); //删除解压后的证书文件
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return Result.ok(null);
	}
	
	
	  private static void deleteFile(File file) throws IOException {
		File[] files = file.listFiles();
		if (files!=null){//如果包含文件进行删除操作
		  for (int i = 0; i <files.length ; i++) {
			  if (!files[i].getName().contains("jy")) {
				  if (files[i].isFile()) {
					  //删除子文件
					  files[i].delete();
				  } else if (files[i].isDirectory()) {
					  //通过递归的方法找到子目录的文件
					  deleteFile(files[i]);
				  }
				  files[i].delete();//删除子目录
			  }
		  }
		}
    }










}
